//
//  XS_BaseMiddleAlertVC.swift
//  Pods
//
//  Created by 韩云智 on 2020/7/15.
//

import UIKit
import RxSwift
import RxCocoa

open class XS_BaseMiddleAlertVC: XS_BaseVC {
    open var customView: UIView!
    open var shouldClose: Bool = false
    open lazy var actionSubject = PublishSubject<(XS_ActionType, (((() -> Void)?)->())?)>()
    
    open override func upConfig() {
        modalTransitionStyle = .crossDissolve
        modalPresentationStyle = .overFullScreen
    }
    open override func upView() {
        view.alpha = 0
        view.backgroundColor = UIColor(white: 0, alpha: 0.7)
    }
    
    open override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        guard let customView = customView else { return }
        if customView.superview == nil {
            view.addSubview(customView)
        }
        if view.alpha == 0 {
            open()
        }
        view.alpha = 1
    }
    /// 点击空白处收起页面
    open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if shouldClose {
            var set = true;
            for touch in touches {
                if touch.view == customView {
                    set = false
                }
            }
            if set {
                actionSubject.onNext((.cancel, { [weak self] completion in self?.close(completion: completion) }))
            }
        }
    }
    /// 打开收起动画
    open func open() {
        UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 15, options: [.curveEaseInOut], animations: {
            self.customView.transform = CGAffineTransform(scaleX: 1, y: 1)
        })
    }
    open func close(completion: (() -> Void)? = nil) {
        UIView.animate(withDuration: 0.25, animations: {
            self.customView.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
            self.view.alpha = 0
        }) { _ in
            self.dismiss(animated: false, completion: completion)
        }
    }
    
    
    open func loadButton(_ img: UIImage?, type: XS_ActionType) -> UIButton {
        let button = UIButton()
        button.adjustsImageWhenHighlighted = false
        if let img = img {
            button.setBackgroundImage(img, for: .normal)
        }
        button.rx.tap.asDriver()
            .throttle(.seconds(2), latest: false)
            .map({[weak self] _ in
                return (type, { [weak self] completion in self?.close(completion: completion) })
            }).drive(actionSubject)
            .disposed(by: disposeBag)
        return button
    }
    
    open func addCustom(_ view: UIView, frame: CGRect) {
        customView.addSubview(view)
        view.snp.makeConstraints { maker in
            maker.left.equalTo(.scale*frame.minX)
            maker.top.equalTo(.scale*frame.minY)
            maker.width.equalTo(.scale*frame.size.width)
            maker.height.equalTo(.scale*frame.size.height)
        }
    }
}
